#!/usr/bin/python
# coding: utf-8
# +-------------------------------------------------------------------
# | 归隐小赵(qq:97777194)
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: gyxz <gyxz2001@qq.com>
# +-------------------------------------------------------------------

#+--------------------------------------------------------------------
#|   GIT版本同步器
#+--------------------------------------------------------------------
import sys,os,json,time

#设置运行目录
os.chdir("/www/server/panel")

#添加包引用位置并引用公共包
sys.path.append("class/")
import public

#from common import dict_obj
#get = dict_obj();

#在非命令行模式下引用面板缓存和session对象
if __name__ != '__main__':
    from BTPanel import cache,session
    
class gyxz_main:
    __plugin_path = "/www/server/panel/plugin/gyxz/"
    __setupPath='plugin/webhook';
    __panelPath = '/www/server/panel';
    __config = 'plugin/gyxz/list.json'

    #构造方法
    def  __init__(self):
        pass
  
    #获取网站列表
    def web(self,get):
        data = public.M('sites').field('name').order('id desc').select()
        html=''
        for arr in data:
            html = html + '<option value="'+arr['name']+'">'+arr['name']+'</option>'
        return {'html':html}
    
    #获取列表
    def GetList(self):
        jsonFile = self.__config;
        if not os.path.exists(jsonFile): return public.returnMsg(False,'配置文件不存在!');
        data = {}
        data = json.loads(public.readFile(jsonFile));
        return sorted(data, key= lambda b:b['addtime'],reverse=True);
		
    #获取列表
    def GetListA(self,get):
        jsonFile = self.__config;
        if not os.path.exists(jsonFile): return public.returnMsg(False,'配置文件不存在!');
        data = {}
        data = json.loads(public.readFile(jsonFile));
        return sorted(data, key= lambda b:b['addtime'],reverse=True);
		
    #获取面板信息
    def url(self,get):
        return {'url':public.GetHost()+":"+public.GetHost(True)}
    
    #获取Hook列表
    def GetListHook(self):
        jsonFile = 'plugin/webhook/list.json';
        if not os.path.exists(jsonFile): return public.returnMsg(False,'配置文件不存在!');
        data = {}
        data = json.loads(public.readFile(jsonFile));
        return sorted(data, key= lambda b:b['addtime'],reverse=True);
        
    #添加Git同步
    def AddHook(self,args):
        if not os.path.exists('plugin/webhook'):
            #安装WebHook /plugin?action=install_plugin  sName=webhook&version=1&type=0
            return public.returnMsg(False,'依赖以下软件,请先安装[%s]' % 'WebHook')
    	#判断参数是否正确传入
        if args.git == "":  return public.returnMsg(False,'Git地址错误')
        git = args.git
        if args.title == "":  return public.returnMsg(False,'标题不能为空')
        title = args.title
        if args.url == "":  return public.returnMsg(False,'目录不能为空')
        url = "/www/wwwroot/"+args.url
        os.chdir(url) #切换工作目录
        public.ExecShell("git init") #初始化
        public.ExecShell("git remote add "+args.url+" "+git) #设置远程仓库地址
        os.chdir("/www/server/panel")
        if 'init' in args:
            #初始化
            os.chdir(url) #切换工作目录
            if args.user == "":  return public.returnMsg(False,'账户不能为空')
            public.ExecShell("git config --global user.name \""+args.user+"\"") #设置账号
            user=args.user
            if args.email == "":  return public.returnMsg(False,'邮箱不能为空')
            email=args.email
	    public.ExecShell("git config --global user.email \""+email+"\"") #设置邮箱
	    os.chdir("/www/server/panel")
            if args.update == "on":
                #是否生成ssh
                if args.ssh_init == "on":
                    #生成SSH
                    if not os.path.isfile('/root/.ssh/id_rsa.pub'):
                        public.ExecShell("ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa -q")

                #准备上传SSH
                if args.token == "":  return public.returnMsg(False,'Token不能为空')
                token = args.token
                ssh = args.ssh_title
                if args.ssh_title == "": ssh = public.GetLocalIp()
                os.chdir("/root/.ssh/") #切换工作目录
                ssh_public = public.ReadFile("id_rsa.pub",mode='r') #读取公钥
                os.chdir("/www/server/panel")
                data={"access_token":token,"key":ssh_public,"title":ssh} #拼接POST参数
                data=json.dumps(data)
                cmd="curl -X POST --header 'Content-Type: application/json;charset=UTF-8' 'https://gitee.com/api/v5/user/keys' -d '"+data+"'"
                arr=public.ExecShell(cmd) #post推送

	#初始化完成
	#添加WebHook脚本
	hook='''#!/bin/bash
        echo ""
        #输出当前时间
        date --date='0 days ago' " %Y-%m-%d %H:%M:%S"
        echo "Start"
        #判断宝塔WebHook参数是否存在
        #git项目路径
        gitPath="'''+url+'''"
        #git 网址
        gitHttp="'''+git+'''"

        echo "Web站点路径：$gitPath"

        #判断项目路径是否存在
        if [ -d "$gitPath" ]; then
                cd $gitPath
                #判断是否存在git目录
                if [ ! -d ".git" ]; then
                        echo "在该目录下克隆 git"
                        git clone $gitHttp gittemp
                        mv gittemp/.git .
                        rm -rf gittemp
                fi
                #拉取最新的项目文件
                git reset --hard origin/master
                        git stash
                git pull '''+args.url+''' master
                        git stash pop
                #设置目录权限
                chown -R www:www $gitPath
                echo "End"
                exit
        else
                echo "该项目路径不存在"
                echo "End"
                exit
        fi'''
	#生成秘钥
	access_key=public.GetRandomString(48)
	arr={}
	arr['title']='git'+title
	arr['access_key']=access_key
	arr['ssh']=hook
	array = self.GetList()
	#Hook添加完成，开始记录
	data = {}
	data['title']='git'+title
	data['addtime']=int(time.time())
	data['access_key']=access_key
	data['url']=url
  	data['git']=git
	array.append(data)
	public.writeFile(self.__config,json.dumps(array))
	return self.Add_Hook(arr)
    
    #删除Hook
    def DelHook(self,get):
        data=self.GetList() #获取数据列表
        newdata=[]
        for hook in data: #循环输出列表
            if hook['access_key'] == get.access_key: continue;
            newdata.append(hook);
        public.writeFile(self.__config,json.dumps(newdata))
  	sys.path.append('plugin/webhook')
        import webhook_main
        webhook_main.webhook_main().DelHook(get)
        return public.returnMsg(True,'删除成功!');
    
    #添加HOOK
    def Add_Hook(self,get):
        data = self.GetListHook();
        hook = {}
        hook['title'] = get['title']
        hook['access_key'] = get['access_key']
        hook['count'] = 0
        hook['addtime'] = int(time.time())
        hook['uptime'] = 0
        jsonFile = self.__setupPath + '/list.json';
        if self.__setupPath + '/script': os.system('mkdir ' + self.__setupPath + '/script');
        shellFile = self.__setupPath + '/script/' + hook['access_key']
        public.writeFile(shellFile,get['ssh'])
        data.append(hook);
        public.writeFile(jsonFile,json.dumps(data))
        return public.returnMsg(True,'添加成功!');
